package top.bulk.delay.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.bulk.delay.entity.OrderEntity;
import top.bulk.delay.mapper.OrderMapper;

import javax.annotation.Resource;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 基于 ScheduledExecutorService 实现
 *
 * @author 散装java
 * @date 2024-08-13
 */
@Component
@Slf4j
public class ScheduledExecutorDelayHandler implements DelayHandler<OrderEntity> {
    @Resource
    private OrderMapper orderMapper;

    /**
     * 定义一个延迟执行器
     */
    private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

    @Override
    public void handle(OrderEntity orderEntity, Integer second) {
        // 添加到延迟任务，DELAY_TIME 秒后执行。只会关闭，添加到任务中的那一个任务id
        executor.schedule(() -> {
            OrderEntity entity = orderMapper.queryById(orderEntity.getId());
            if (entity.canClose(second)) {
                orderMapper.closeOrder(orderEntity.getId());
            }
            // 模拟处理订单
            log.info("订单：{} 关闭成功", orderEntity.getOrderNo());
        }, second, TimeUnit.SECONDS);
    }
}
